<?php
	session_start();

	function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
		// open raw memory as file so no temp files needed, you might run out of memory though
		$f = fopen('php://memory', 'w'); 


		//fputcsv($f, array_keys($array), $delimiter);

		// loop over the input array
		foreach ($array as $line) 
		{ 
			// generate csv lines from the inner arrays
			fputcsv($f, $line, $delimiter); 
		}
		// rewrind the "file" with the csv lines
		fseek($f, 0);
		// tell the browser it's going to be a csv file
		header('Content-Type: application/csv');
		// tell the browser we want to save it instead of displaying it
		header('Content-Disposition: attachement; filename="'.$filename.'"');
		// make php send the generated csv lines to the browser
		fpassthru($f);
	}


	if (!isset($_SESSION['login']) && !$_SESSION['login'] == true) {
		header ("Location: index.php");
	}

	include("config.php");

	if(!isset($_GET['IDS']))
		exit;

	$IDS = $_GET['IDS'];
	$IDS = trim($IDS, '"');
	$IDS = explode(',', $IDS);
	$companyID = $_SESSION['companyID'];
	$sql = 'SELECT Innovation.Name AS InnovationsNamn, Innovation.CustomerName AS Kundnamn, Innovation.ContactName as Kontaktperson, Innovation.Created AS Skapad, T1.UserName as SkapadAv, Innovation.Recommendation AS Rekommendation, Innovation.Problem AS Problem, Innovation.Solution AS Lösning, Innovation.CustomerValue AS Kundvärde, Innovation_TimeFrame.Value AS Tidsplan, Innovation_NextStep.Value AS NästaSteg
	FROM Innovation INNER JOIN (SELECT User.ID, User.Name as UserName, Company.ID as CompanyID, Company.Name AS CompanyName FROM User INNER JOIN Company ON User.CompanyID = Company.ID) AS T1 ON Innovation.OwnerID = T1.ID AND T1.CompanyID = ? INNER JOIN Innovation_TimeFrame ON Innovation.TimeFrameID = Innovation_TimeFrame.ID INNER JOIN Innovation_NextStep ON Innovation.NextStepID = Innovation_NextStep.ID WHERE Innovation.ID = ? ORDER BY Innovation.ID';

	$stmt = $con->prepare($sql);
	
	$array = [];
	$headersAdded = false;
	for ($i = 0; $i < count($IDS); $i++)
	{
		$stmt->bind_param("ii",$companyID, $IDS[$i]);
		$stmt->execute();
		$result = $stmt->get_result();
		while($row = $result->fetch_array(MYSQLI_ASSOC))
		{
			if(!$headersAdded)
			{	
				$headersAdded  = true;
				array_push($array, array_keys($row));
			}
			array_push($array, array_values($row));
		}
	}

	$companyName = $_SESSION['companyName'];

	$h = "2";// Hour for time zone goes here e.g. +7 or -4, just remove the + or -
	$hm = $h * 60; 
	$ms = $hm * 60;
	$gmdate = gmdate("Y-m-d H-i", time()+($ms)); // the "-" can be switched to a plus if that's what your time zone is.

	$filename = $companyName . " - " . $gmdate . ".csv";

	array_to_csv_download($array, $filename);
	
	mysqli_close($con);
	
?>